package com.qianxin.ids.idam.am.authn.factors.cass.upsso.rest;

import cn.hutool.core.codec.Base64;
import com.gitee.starblues.realize.PluginUtils;
import com.qianxin.ids.idam.am.authn.api.context.IContextService;
import com.qianxin.ids.idam.am.authn.api.factors.AuthnFactorInstance;
import com.qianxin.ids.idam.am.authn.api.utils.AuthnFactorInstanceUtils;
import com.qianxin.ids.idam.am.authn.factors.cass.upsso.PluginCassUpSsoAuthnFactorImpl;
import com.qianxin.ids.idam.am.authn.factors.cass.upsso.api.CassCommon;
import com.qianxin.ids.idam.am.authn.factors.cass.upsso.api.CassUpSsoProperties;
import com.qianxin.ids.idam.am.session.api.entity.AuthnContext;
import com.qianxin.ids.idam.framework.common.WhiteListAnnotation;
import com.qianxin.ids.idam.sdk.utils.StringUtils;
import com.qianxin.ids.idam.sdk.view.SimpleResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@RestController
@Slf4j
public class PluginCassSsoController {


    @Autowired
    private PluginUtils pluginUtils;

    private IContextService contextService;

    @Autowired
    private PluginCassUpSsoAuthnFactorImpl pluginCassUpSsoAuthnFactor;
    @PostConstruct
    private void init() {
        contextService = pluginUtils.getMainBean(IContextService.class);
    }

    /**
     * 获取完整SSO路径，包含usertoken等
     * @return
     */
    @GetMapping("/api/v1/sso/cass/url")
    public ResponseEntity<SimpleResponseData<String>> getCodeByToken(){
        // TODO  直接从会话中获取？ 能否获取?
        AuthnContext context = contextService.getAuthnContextByRequest();
        SimpleResponseData<String> response = new SimpleResponseData<>();
        if (context == null || context.getBizUserEntity() == null) {
            response.setMessage("未获取到账号信息");
            return ResponseEntity.ok(response);
        }
        String user = context.getBizUserEntity().getCode();
        // 同步操作，可能会等待，需要设置超时
        String token = contextService.getAuthnContextByRequest().getAttribute(CassCommon.TOKEN);
        String instanceId = contextService.getAuthnContextByRequest().getAttribute(CassCommon.INSTANCE);
        String session = contextService.getAuthnContextByRequest().getAttribute(CassCommon.SESSION);
        String userToken = contextService.getAuthnContextByRequest().getAttribute(CassCommon.USER_TOKEN);
        log.info("会话【{}】，获取user【{}】", contextService.getAuthnContextByRequest().getId(), user);
        log.info("/api/v1/sso/cass/url 会话中尝试获取的UserToken [{}]", userToken);
        AuthnFactorInstance instance = AuthnFactorInstanceUtils.getFactorInstance(instanceId);
        CassUpSsoProperties properties = CassUpSsoProperties.parse(instance);
        if (StringUtils.isEmpty(userToken)){
            userToken = pluginCassUpSsoAuthnFactor.getUserToken(properties, session,token);
        }
        // 访问门户是userName=  ,并且携带cookie
//        String ssoParam = properties.getSsoUrl()+"?userToken=" + userToken + "&from=prod&userName="+ user
//                + "&cookie="+ Base64.encode("SESSION="+session);
        String ssoParam = properties.getSsoUrl()+"?code=12345&from=prod&userToken="+userToken+
                "&userName="+user+
                "&cookie="+ Base64.encode("SESSION="+session);
        log.info("/uiapi/v1/cass/sso/url 输出最终返回SSO地址为： [{}] ", ssoParam);
        return ResponseEntity.ok(SimpleResponseData.ok(ssoParam));


//        String code = pluginCassUpSsoAuthnFactor.getCode(user,
//                context.getAttribute(CassCommon.INSTANCE) ,
//                context.getAttribute(CassCommon.IAM_SESSION),
//                context.getAttribute(CassCommon.TOKEN));
//        // 从缓存中获取  user -> code 对应关系，如果不存在或者存在做不同处理
//        // 存在key
//        if (StringUtils.isNotBlank(code)){
//            CassCodeCache.removeUser(user);
//            return ResponseEntity.ok(SimpleResponseData.ok(code));
//        }else{
//            // code 不存在，尚未回调
//            response.setMessage(" code尚未接收到，请稍后再试，或重新登陆后再试");
//            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
//        }
    }

//    /**
//     * 对外接口
//     * 接口是否应该在 runtime 侧请求？
//     *
//     * @param code
//     * @param state 选填；可以是希望认证中心透传返回的原始请求的URL或其他任意字符串  ？
//     *              对接方说此字段不能传递。
//     * @return
//     */
//    @GetMapping(value = "/api/scim/getCode/callback")
//    @WhiteListAnnotation("/api/scim/getCode/callback")
//    public ResponseEntity<JSONObject> getCode(@RequestParam("state") String user, @RequestParam("code") String code){
//        pluginCassUpSsoAuthnFactor.putCode(user, code);
//        return new ResponseEntity<>(null, HttpStatus.OK);
//    }
//
//
//    @GetMapping(value = "/api/scim/getCodeByUserCode")
//    @WhiteListAnnotation("/api/scim/getCode/callback")
//    public ResponseEntity<JSONObject> getCode(@RequestParam("state") String user, @RequestParam("code") String code){
//        pluginCassUpSsoAuthnFactor.putCode(user, code);
//        return new ResponseEntity<>(null, HttpStatus.OK);
//    }

}
